package cn.ultrarisk.scadmin.manager.web.controller.solr;

import cn.ultrarisk.scadmin.manager.biz.zookeeper.dao.ZkNodeDAO;
import cn.ultrarisk.scadmin.manager.biz.zookeeper.entity.ZkNode;
import cn.ultrarisk.scadmin.manager.biz.zookeeper.operator.ZookeeperOperator;
import cn.ultrarisk.scadmin.manager.biz.zookeeper.service.ZkNodeService;
import cn.ultrarisk.scadmin.manager.web.controller.BaseController;
import cn.ultrarisk.scadmin.manager.web.dto.solr.SolrConfigDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

/**
 * ConfigController
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/4/17
 * @since V1.0
 */
@Controller
@RequestMapping(value = "/solr/config")
public class ConfigController extends BaseController {
    @Autowired
    private ZkNodeDAO zkNodeDAO;
    @Autowired
    private ZkNodeService zkNodeService;
    @Autowired
    private ZookeeperOperator zookeeperOperator;

    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseEntity<List<ZkNode>> list() {
        List<ZkNode> configNodes = zkNodeDAO.findByLikePath("/configs%", 0, true, ZkNode.ID, ZkNode.PARENT_ID, ZkNode.PATH);
        return getOkResponseEntity(configNodes);
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<ZkNode> get(@PathVariable("id") Integer id) {
        ZkNode node = zkNodeDAO.get(id);
        return getOkResponseEntity(node);
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    public ResponseEntity<String> update(@PathVariable("id") Integer id, @RequestBody SolrConfigDTO dto) {
        zkNodeService.updateData(id, dto.getData());
        return getOkResponseEntity();
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<String> delete(@PathVariable("id") Integer id) {
        zkNodeService.delete(id, 0);
        return getOkResponseEntity();
    }

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<String> upload(MultipartHttpServletRequest request) throws IOException {
        String path = request.getParameter("path");
        Collection<MultipartFile> files = request.getFileMap().values();
        zkNodeService.uploadFiles(path, files, 0);
        return getOkResponseEntity();
    }
}
